package com.suncnpap.base.controller;




import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.app.util.common.Constants;
import com.app.util.common.FileUtil;
import com.app.util.common.HandlerResult;
import com.app.util.common.ObjUtil;
import com.app.util.common.PathUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.common.Ticket;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.system.model.Admin;
import com.suncnpap.system.model.Menu;
import com.suncnpap.system.model.MenuRole;
import com.suncnpap.system.service.AdminService;
import com.suncnpap.system.service.MenuRoleService;
import com.suncnpap.system.service.MenuService;

@Controller
@Api(description = "用户登录,退出处理")
public class LoginController {

	@Autowired
	MainHelper mainHelper;
	
	@Autowired
	AdminService adminService;
	
	@Autowired
	MenuRoleService menuRoleService;
	
	@Autowired
	MenuService menuService;
	
	@Autowired
	ReaderService readerService;
	
	@RequestMapping(value="/toLogin",method=RequestMethod.POST)
	public void login(HttpServletRequest request,HttpServletResponse response) {
		
		HandlerResult result = new HandlerResult();
		String errInfo = null;

		String password = request.getParameter("strPd");
		String username = request.getParameter("userId");
		String strSchoolId = request.getParameter("strSchoolId");
		
		result = login(username,password,strSchoolId);
	    
	    if(result.getCode()!=0) {		//登录失败
	    	/**
			 * 记录登录异常信息
			 */
			loginErrorLog(username,password,errInfo);
	    }
	    
	    ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 记录登录异常日志
	 * @param username
	 * @param password
	 * @param errInfo
	 */
	private void loginErrorLog(String username,String password,String errInfo){
		
	}
	
	/**
	 * 用户登录处理
	 * @param username
	 * @param password
	 * @return
	 */
	
	private HandlerResult login(String username,String password, String strSchoolId) {
		
		HandlerResult result = new HandlerResult();
		String errInfo = "";
			
		Admin user = null;
		Reader reader = null;
		if(username.equals(Constants.INIT_USER_ID)) {	//初始化管理员
			user = new Admin();
			user.toInitRainbow();
		}else {
			user = adminService.findByUserId(username, strSchoolId);
			if(user==null){
				reader = readerService.findByCardNumber(username, strSchoolId);
			}
		}

		// 如果查询不到返回null，可以通过用户名和卡号登录
		if(user==null && reader==null){
			result.setCode(1);
			errInfo="用户不存在或用户名/密码错误";
			result.setMessage(errInfo);
			return result;
		}
			
			
		if(user!=null){
			String enPassword = Admin.getMd5Password(password, user.getStrSalt());
			if(!enPassword.equals(user.getStrPassword())){
				result.setCode(1);
				errInfo="密码错误";
				result.setMessage(errInfo);
				return result;
			}
			
			result.put("token", Ticket.getRandom(user.getStrUser(), Ticket.getTicket(30)));
	    	result.put("reftoken", Ticket.getRandom(user.getStrUser(), Ticket.getTicket(30)));
			GlobaUser.setGlobaUser((String)result.getMap().get("token"), user);	
			
		}
		
		if(reader!=null){
			String enPassword = Reader.getMd5Password(password, reader.getStrSalt());
			if(!enPassword.equals(reader.getStrPassword())){
				result.setCode(1);
				errInfo="密码错误";
				result.setMessage(errInfo);
				return result;
			}
			
			result.put("token", Ticket.getRandom(reader.getStrCardNumber(), Ticket.getTicket(30)));
	    	result.put("reftoken", Ticket.getRandom(reader.getStrCardNumber(), Ticket.getTicket(30)));
			GlobaUser.setGlobaReader((String)result.getMap().get("token"), reader);	
			
		}
		
		
		
		return result;
		
	}
	
	
	@RequestMapping(value="/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) {
		
//		Globa.removeAttribute(Constants.SESSION_USER);
		
		HandlerResult result = new HandlerResult();

		try{
			String token = request.getHeader("token");
			Ticket.getTicketMap().remove(token);
			GlobaUser.removeGlobaUser(token);
		}catch(Exception e){
			result.setCode(1);
			result.setMessage("");
		}
		
		ResponseUtil.writeJson(result, response);
	}
	
	private List<Map<String,Object>> creatJsonTree(List<Menu> menuList){
		List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>();
		if(menuList != null){
			for(Menu obj: menuList){
				Map<String,Object> tempMap = new HashMap<String,Object>();
				
				tempMap.put("strParentNodeId", obj.getStrId());
				tempMap.put("strParentNodeName", obj.getStrName());
				List<Map<String,Object>> tempJson = creatJsonTree(obj.getChildren());
				if(tempJson!=null && tempJson.size()>0){
					tempMap.put("children", tempJson);
				}
				tempMap.put("expand", false);
				tempList.add(tempMap);
			}
		}
		return tempList;
	}
	
	private List<Menu> creatMenuTree(List<Menu> menuList,Map<String, List<Menu>> menuListMap){
		List<Menu> list=null;
		for(int i=0;menuList!=null&&i<menuList.size();i++){
			Menu obj=menuList.get(i);
			list=list==null?new ArrayList<Menu>():list;
			obj.setChildren(creatMenuTree(menuListMap.get(obj.getStrId()),menuListMap));
				
			list.add(obj);
		}
		return list;
	}
}
